package com.chenliang.thread.service.impl;

import com.chenliang.thread.service.CallService;
import com.chenliang.thread.service.ThreadPoolExecutorService;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;

/**
 * @program: springboot_thread_002
 * @description:
 * @author: 陈亮
 * @create: 2022-05-15 22:09
 */
@Service
public class CallServiceImpl implements CallService {


    @Resource
    private TaskExecutor taskExecutor;

    @Resource
    private ThreadPoolExecutorService threadPoolExecutorService;

    @Override
    public void callOne() {
        for (int i = 0; i < 10; i++) {

            int finalI = i;
            taskExecutor.execute(() -> {
                System.out.println("这是" + Thread.currentThread().getName() + "在" + finalI + "次打印");
                try {
                    Thread.sleep(6000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

    }


    @Override
    public void callTwo() {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        System.out.println("我是:" + Thread.currentThread().getName() + ",我正在执行threadPoolExecutorService");
        threadPoolExecutorService.testOne(countDownLatch);
        threadPoolExecutorService.testTwo(countDownLatch);
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("三个都执行结束了");

        /**
         * 执行结果:
         * 我是:chenliang-1,我正在执行threadPoolExecutorService
         * 三个都执行结束了
         * 我是:chenliang-2,我正在执行发送短信任务
         * 我是:chenliang-3,我正在执行发送邮件任务
         *
         * 如果做到把 "三个都执行结束了" 放在最后执行呢?
         * 使用 CountDownLatch countDownLatch,结果变为:
         *
         * 我是:chenliang-1,我正在执行threadPoolExecutorService
         * 我是:chenliang-3,我正在执行发送邮件任务
         * 我是:chenliang-2,我正在执行发送短信任务
         * 三个都执行结束了
         *
         * 有没有风险呢?
         *
         *
         */

    }


    @Override
    public void callThree() {
        
        System.out.println("我是:" + Thread.currentThread().getName() + ",我准备往下执行了");
        
            CompletableFuture.runAsync(() -> System.out.println("我是:" + Thread.currentThread().getName() + ",我正在测试CompletableFuture.runAsync调用多线程"),taskExecutor);

    }
}
